package com.example.foodwebbackend.controller;

import com.example.foodwebbackend.dto.ApiResponse;
import com.example.foodwebbackend.dto.PageRequest;
import com.example.foodwebbackend.dto.PageResponse;
import com.example.foodwebbackend.dto.UserRequest;
import com.example.foodwebbackend.entity.User;
import com.example.foodwebbackend.service.UserService;
import com.example.foodwebbackend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin/users")
@CrossOrigin(origins = "*")
public class AdminUserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 分页获取用户列表
     */
    @GetMapping
    public ApiResponse<PageResponse<User>> getUsers(
        @RequestParam(defaultValue = "1") int page,
        @RequestParam(defaultValue = "20") int size,
        @RequestParam(required = false) String search,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            // 暂时注释权限验证，方便调试
            // if (!validateAdminToken(token)) {
            //     return ApiResponse.unauthorized("无权限访问");
            // }
            
            PageRequest pageRequest = new PageRequest(page, size, search);
            PageResponse<User> users = userService.getUsersWithPagination(pageRequest);
            return ApiResponse.success(users);
        } catch (Exception e) {
            return ApiResponse.error("获取用户列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取用户详情
     */
    @GetMapping("/{id}")
    public ApiResponse<User> getUserById(
        @PathVariable Integer id,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            // 暂时注释权限验证
            // if (!validateAdminToken(token)) {
            //     return ApiResponse.unauthorized("无权限访问");
            // }
            
            User user = userService.findById(id);
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            return ApiResponse.success(user);
        } catch (Exception e) {
            return ApiResponse.error("获取用户详情失败: " + e.getMessage());
        }
    }

    /**
     * 添加用户
     */
    @PostMapping
    public ApiResponse<User> addUser(
        @RequestBody UserRequest request,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            // 暂时注释权限验证
            // if (!validateAdminToken(token)) {
            //     return ApiResponse.unauthorized("无权限访问");
            // }
            
            if (request.getUsername() == null || request.getPassword() == null) {
                return ApiResponse.error("用户名和密码不能为空");
            }
            
            if (userService.existsByUsername(request.getUsername())) {
                return ApiResponse.error("用户名已存在");
            }
            
            User user = userService.createUser(request);
            return ApiResponse.success("用户添加成功", user);
        } catch (Exception e) {
            return ApiResponse.error("添加用户失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public ApiResponse<User> updateUser(
        @PathVariable Integer id,
        @RequestBody UserRequest request,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            // 暂时注释权限验证
            // if (!validateAdminToken(token)) {
            //     return ApiResponse.unauthorized("无权限访问");
            // }
            
            User existingUser = userService.findById(id);
            if (existingUser == null) {
                return ApiResponse.error("用户不存在");
            }
            
            // 检查用户名是否已被其他用户使用
            if (request.getUsername() != null && 
                !request.getUsername().equals(existingUser.getUsername()) &&
                userService.existsByUsername(request.getUsername())) {
                return ApiResponse.error("用户名已存在");
            }
            
            User updatedUser = userService.updateUser(id, request);
            return ApiResponse.success("用户更新成功", updatedUser);
        } catch (Exception e) {
            return ApiResponse.error("更新用户失败: " + e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public ApiResponse<?> deleteUser(
        @PathVariable Integer id,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            // 暂时注释权限验证
            // if (!validateAdminToken(token)) {
            //     return ApiResponse.unauthorized("无权限访问");
            // }
            
            User user = userService.findById(id);
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            userService.deleteUser(id);
            return ApiResponse.success("用户删除成功");
        } catch (Exception e) {
            return ApiResponse.error("删除用户失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除用户
     */
    @DeleteMapping("/batch")
    public ApiResponse<?> batchDeleteUsers(
        @RequestBody Map<String, List<Integer>> request,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            // 暂时注释权限验证
            // if (!validateAdminToken(token)) {
            //     return ApiResponse.unauthorized("无权限访问");
            // }
            
            List<Integer> userIds = request.get("userIds");
            if (userIds == null || userIds.isEmpty()) {
                return ApiResponse.error("请选择要删除的用户");
            }
            
            int deletedCount = userService.batchDeleteUsers(userIds);
            return ApiResponse.success("成功删除 " + deletedCount + " 个用户");
        } catch (Exception e) {
            return ApiResponse.error("批量删除用户失败: " + e.getMessage());
        }
    }

    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/reset-password")
    public ApiResponse<?> resetPassword(
        @PathVariable Integer id,
        @RequestBody Map<String, String> request,
        @RequestHeader(value = "Authorization", required = false) String token
    ) {
        try {
            // 暂时注释权限验证
            // if (!validateAdminToken(token)) {
            //     return ApiResponse.unauthorized("无权限访问");
            // }
            
            String newPassword = request.get("newPassword");
            if (newPassword == null || newPassword.trim().isEmpty()) {
                return ApiResponse.error("新密码不能为空");
            }
            
            User user = userService.findById(id);
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            userService.resetPassword(id, newPassword);
            return ApiResponse.success("密码重置成功");
        } catch (Exception e) {
            return ApiResponse.error("重置密码失败: " + e.getMessage());
        }
    }

    /**
     * 验证管理员token
     */
    private boolean validateAdminToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return false;
            }
            
            String jwt = token.substring(7);
            String userType = jwtUtil.getUserTypeFromToken(jwt);
            return "admin".equals(userType);
        } catch (Exception e) {
            return false;
        }
    }
} 